/*
 *  Copyright 2001-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ar.uba.fi.posgrado.economy.web.action.debt;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.json.JSONArray;

import ar.uba.fi.posgrado.common.dto.JSONable;
import ar.uba.fi.posgrado.common.exception.PosgradoException;
import ar.uba.fi.posgrado.economy.model.Benefit;
import ar.uba.fi.posgrado.economy.model.BenefitStatus;
import ar.uba.fi.posgrado.economy.model.Discount;
import ar.uba.fi.posgrado.economy.service.BenefitService;
import ar.uba.fi.posgrado.economy.service.DiscountService;
import ar.uba.fi.posgrado.economy.web.form.debt.DebtForm;
import ar.uba.fi.posgrado.economy.web.util.BenefitToBenefitDTOTransformer;
import ar.uba.fi.posgrado.economy.web.util.DiscountToDiscountDTOTransformer;

/**
 * Action que obtiene los beneficios y descuentos seleccionados
 * para asi calcular:<br>
 * <ul>
 *  <li>Beneficios Disponibles</li>
 *  <li>Beneficios Seleccionados (recibidos como Ids)</li>
 *  <li>Descuentos Disponibles</li>
 *  <li>Descuentos Seleccionados (recibidos como Ids)</li>
 * </ul>
 * 
 * Los popula via JSON.<br>
 * La estructura de respuesta es asi:<br>
 * <code>
 * [
 *      [
 *              {"value":"15.0","description":"Benef_1","id":"1","valueOrPercentageLabel":"Valor"},
 *              {"value":"18.0","description":"Benef_2","id":"2","valueOrPercentageLabel":"Valor"}
 *      ],
 *      [
 *              {"value":"8.0","description":"Benef_3","id":"5","valueOrPercentageLabel":"Porcentaje"},
 *      ],
 *      [
 *              {"value":"60.0","description":"Desc_1","id":"1","valueOrPercentageLabel":"Porcentaje"},
 *      ],
 *      [
 *              {"value":"100.0","description":"Desc_2","id":"2","valueOrPercentageLabel":"valor"},
 *      ],
 * ]
 * </code>
 * <br>
 * Es decir, de esta manera:<br>
 * <b>[[beneficios_disponibles],[beneficios_seleccionados],[descuentos_disponibles],[descuentos_seleccionados]]</b><br>
 * <b>Las posiciones <i>SON</i> importantes</b>
 * <br>
 * <br>
 *  Este Action sirve tanto para altas, como modificaciones. Es indistinto.<br> 
 * 
 * @author nicolas.gonzalez
 * @see Action
 */
public class PopulateBenefitsAndDiscountsAction extends Action {

    /** Logger */
    private static Logger logger = Logger.getLogger(PopulateBenefitsAndDiscountsAction.class);
    
    private BenefitService benefitService;
    private DiscountService discountService;

    /**
     * IoC
     * @param benefitService the benefitService to set
     */
    public void setBenefitService(BenefitService benefitService) {
        this.benefitService = benefitService;
    }

    /**
     * IoC
     * @param discountService the discountService to set
     */
    public void setDiscountService(DiscountService discountService) {
        this.discountService = discountService;
    }
    
    
    
    /**
     * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    @SuppressWarnings("unchecked")
    public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("Por buscar los beneficios y descuentos para la deuda ...");
        }
        DebtForm form = (DebtForm)actionForm;
        List<Long> selectedDiscountIds = form.getSelectedDiscountsIds();
        // Todos los seleccionados. Pueden no haber seleccionados, al menos la primera vez....
        List<Discount> discountsSelected = this.discountService.getDiscountsByIds(selectedDiscountIds);
        List<Long> selectedBenefitIds = form.getSelectedBenefitsIds();
        List<Benefit> benefitsSelected = this.benefitService.getBenegitsByIds(selectedBenefitIds);
        
        Transformer benefitTransformer = transformerForBenefit();
        Transformer discountTransformer = transformerForDiscount();
        
        Collection<Discount> discountsAvailable = this.getAvailableDiscounts(discountsSelected);
        Collection<Benefit> benefitsAvailable = this.getAvailableBenefits(benefitsSelected);
        // Ya tengo las 4 colecciones
        JSONArray availBenefitsArray = this.assembleJsonArray(benefitsAvailable, benefitTransformer);
        JSONArray selBenefitsArray = this.assembleJsonArray(benefitsSelected, benefitTransformer);
        JSONArray availDiscountsArray = this.assembleJsonArray(discountsAvailable, discountTransformer);
        JSONArray selDiscountsArray = this.assembleJsonArray(discountsSelected, discountTransformer);
        
        // Aca se ponen los 4 JSON objects (q son Arrays cada uno)
        JSONArray masterArray = new JSONArray();
        masterArray.put(availBenefitsArray);
        masterArray.put(selBenefitsArray);
        masterArray.put(availDiscountsArray);
        masterArray.put(selDiscountsArray);
        
        // Set content to JSON
        response.setContentType("application/x-json");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("X-JSON", masterArray.toString());

        if (logger.isDebugEnabled()) {
            logger.debug("Beneficios y descuentos armados para la deuda finalizado");
        }
        return mapping.findForward("blank");        
    }
    
    
    @SuppressWarnings("unchecked")
    private Collection<Benefit> getAvailableBenefits(List<Benefit> selectedBenefits) throws PosgradoException {
        // Todos los activos
        List<Benefit> activeBenefits = this.benefitService.getBenefitsByStatus(BenefitStatus.Active);
        // Aca estan los disponibles
        Collection<Benefit> available = CollectionUtils.subtract(activeBenefits, selectedBenefits);
        
        return available;
    }

    @SuppressWarnings("unchecked")
    private Collection<Discount> getAvailableDiscounts(List<Discount> selectedDiscounts) throws PosgradoException {
        // Todos
        List<Discount> allDiscounts = this.discountService.getAll();
        // Aca estan los disponibles
        Collection<Discount> available = CollectionUtils.subtract(allDiscounts, selectedDiscounts);
        
        return available;
    }
    
    /**
     * Arma una {@link JSONArray} a partir de los objectos aplicando un {@link Transformer}
     * especifico.<br>
     * @param objects
     * @param transformer Tiene q transformar a algo {@link JSONable}
     * @return
     */
    @SuppressWarnings("unchecked")
    private JSONArray assembleJsonArray(Collection objects, Transformer transformer) {
        JSONArray response = new JSONArray();

        CollectionUtils.transform(objects, transformer);
        
        for (Iterator iterator = objects.iterator(); iterator.hasNext();) {
            JSONable jsonable = (JSONable) iterator.next();
            
            response.put(jsonable.toJSON());
        }
        
        return response;
    }
    
    
    private static Transformer transformerForBenefit() {
        return new BenefitToBenefitDTOTransformer();
    }

    private static Transformer transformerForDiscount() {
        return new DiscountToDiscountDTOTransformer();
    }

}
